/**
 * @file feature_extractor.c
 * @brief 音频特征提取模块实现
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "feature_extractor.h"
#include "score_engine.h"
#include "webrtc_vad.h"


// 引入FFT函数的声明
extern int CFFTN(float *afftData, int len, int isign);



/* ---------------- YIN 基频检测 ---------------- */
#include <float.h>

/*
 * 简易 YIN 实现 (CMND 方法)
 * 输入 : audio      - 预处理后的浮点 PCM, 范围[-1,1]
 *        len        - 帧长度 (如 2048)
 *        sample_rate- 采样率 (如 48000)
 * 返回 : 基频 Hz, 若未检测到则返回 0
 */
static float yin_detect_f0(const FeatureSet* features, int len, int sample_rate)
{
    if (!features || !features->fft_data || len < 16) return 0.0f;

    /* 搜索范围: 70Hz ~ 650Hz 对应滞后 */
    int tau_min = sample_rate / 650;
    int tau_max = sample_rate /  70;
    if (tau_max >= len/2) tau_max = len/2 - 1;
    if (tau_min < 2 || tau_min >= tau_max) return 0.0f;

    /* ---- 使用 FeatureSet 内部缓冲 ---- */
    if (!features->yin_diff || !features->yin_cmnd || !features->yin_tmp) {
        return 0.0f; /* 缓冲未分配 */
    }
    float* diff = features->yin_diff;
    float* cmnd = features->yin_cmnd;

    /* 1) 构造功率谱到临时缓冲，仅遍历 0..N/2 */
    int nfft = len;
    float* fftbuf = features->yin_tmp; /* 复数数组 len*2 */
    int half = nfft / 2;

    for (int k = 0; k <= half; ++k) {
        float re = features->fft_data[2 * k];
        float im = features->fft_data[2 * k + 1];
        float mag2 = re * re + im * im;
        /* 正频 */
        fftbuf[2 * k] = mag2;
        fftbuf[2 * k + 1] = 0.0f;
        /* 负频镜像（跳过 k=0 与 Nyquist 点）*/
        if (k > 0 && k < half) {
            int idx = nfft - k;
            fftbuf[2 * idx] = mag2;
            fftbuf[2 * idx + 1] = 0.0f;
        }
    }
    /* 清零未触及的中间区间（只在奇数 nfft 时存在，或安全起见）*/
    memset(&fftbuf[2 * (half + 1)], 0, (nfft - half - 1) * 2 * sizeof(float));

    /* 3) IFFT 得到自相关 */
    CFFTN(fftbuf, nfft, -1);
    float invNfft = 1.0f / nfft;
    float r0 = fftbuf[0] * invNfft;

    diff[0] = 0.0f;
    for (int tau = 1; tau <= tau_max; ++tau) {
        float r = fftbuf[2 * tau] * invNfft;
        diff[tau] = 2.0f * (r0 - r);
    }

    /* 2) 累计平均归一化差分 CMND(tau) */
    cmnd[0] = 1.0f;
    double running_sum = 0.0;
    for (int tau = 1; tau <= tau_max; ++tau) {
        running_sum += diff[tau];
        cmnd[tau] = (running_sum > 0.0) ? diff[tau] * tau / running_sum : 1.0f;
    }

    /* 3) 寻找第一个低于阈值的局部最小 */
    const float THR = 0.20f;   /* 阈值进一步放宽 */
    int tau_est = -1;
    for (int tau = tau_min + 1; tau <= tau_max; ++tau) {
        if (cmnd[tau] < THR && cmnd[tau] < cmnd[tau-1]) {
            while (tau + 1 <= tau_max && cmnd[tau+1] < cmnd[tau]) tau++;
            tau_est = tau;
            break;
        }
    }

    /* 若未找到满足阈值的峰，则退而求其次使用全局最小值 */
    if (tau_est == -1) {
        float min_val = FLT_MAX;
        int   min_tau = -1;
        for (int tau = tau_min; tau <= tau_max; ++tau) {
            if (cmnd[tau] < min_val) { min_val = cmnd[tau]; min_tau = tau; }
        }
        /* 只有在差分明显呈周期性 (min_val < 0.8) 时才认为有效 */
        if (min_val < 0.6f) tau_est = min_tau;
    }

    float f0 = 0.0f;
    if (tau_est > 0) {
        /* 4) 抛物线插值细化 tau */
        if (tau_est > 1 && tau_est < tau_max) {
            float x0 = cmnd[tau_est-1];
            float x1 = cmnd[tau_est];
            float x2 = cmnd[tau_est+1];
            float denom = (2.0f * x1 - x2 - x0);
            if (fabsf(denom) > 1e-12f) {
                float delta = 0.5f * (x2 - x0) / denom;
                if (fabsf(delta) <= 1.0f) tau_est = tau_est + delta;
            }
        }
        f0 = (float)sample_rate / (float)tau_est;
    }

    /* 无需释放静态缓冲 */
    return f0;
}


// 创建特征集合
FeatureSet* create_feature_set(int max_frame_size, int sample_rate) {
    FeatureSet* features = (FeatureSet*)malloc(sizeof(FeatureSet));
    if (!features) {
        return NULL;
    }
    
    // 初始化基本属性（包括所有固定长度数组）
    memset(features, 0, sizeof(FeatureSet));
    
    // 保存参数
    features->max_frame_size = max_frame_size;
    features->sample_rate = sample_rate;
    
    // 分配FFT频谱内存 (dB) 和线性幅度谱内存
    features->spectrum_fft = (float*)malloc(max_frame_size * sizeof(float));
    features->spectrum_mag = (float*)malloc(max_frame_size * sizeof(float));
    if (!features->spectrum_fft || !features->spectrum_mag) {
        if (features->spectrum_fft) free(features->spectrum_fft);
        if (features->spectrum_mag) free(features->spectrum_mag);
        free(features);
        return NULL;
    }
    memset(features->spectrum_fft, 0, max_frame_size * sizeof(float));
    memset(features->spectrum_mag, 0, max_frame_size * sizeof(float));
    
    // 分配窗函数缓冲区
    features->window_buffer = (float*)malloc(max_frame_size * sizeof(float));
    if (!features->window_buffer) {
        free(features->spectrum_fft);
        free(features->spectrum_mag);
        free(features);
        return NULL;
    }
    
    // 预先计算汉宁窗
    for (int i = 0; i < max_frame_size; i++) {
        features->window_buffer[i] = 0.5f * (1.0f - cosf(2.0f * M_PI * i / (max_frame_size - 1)));
    }
    
    // 分配FFT数据缓冲区（实部虚部交替存储，所以大小是max_frame_size*2）
    features->fft_data = (float*)malloc(max_frame_size * 2 * sizeof(float));
    if (!features->fft_data) {
        free(features->window_buffer);
        free(features->spectrum_fft);
        free(features->spectrum_mag);
        free(features);
        return NULL;
    }
    
    // -------- 新增：为对数重采样缓冲区预分配内存 --------
    int max_bins = max_frame_size / 2; // Nyquist 以下最大线性bin数量
    features->log_indices = (float*)malloc(max_bins * sizeof(float));
    features->log_resampled_full = (float*)malloc(max_bins * sizeof(float));
    if (!features->log_indices || !features->log_resampled_full) {
        if (features->log_indices) free(features->log_indices);
        if (features->log_resampled_full) free(features->log_resampled_full);
        free(features->fft_data);
        free(features->window_buffer);
        free(features->spectrum_fft);
        free(features->spectrum_mag);
        free(features);
        return NULL;
    }

    features->num_freq_bins = 0; // 初始化为0，首次计算时再填充
    features->min_bin = 0;
    
    // -------- VAD 相关默认设置 --------
    features->vad_method = 1;      // 0- WebRTC, 1- 纯能量法
    features->vad_energy_th = 0.02f; // 归一化 RMS 阈
    
    features->vad_pcm_buf = NULL;
    features->vad_pcm_size = 0;
    
    /* --------- 为 YIN 缓冲区分配内存 --------- */
    features->yin_diff = (float*)malloc((max_frame_size + 1) * sizeof(float));
    features->yin_cmnd = (float*)malloc((max_frame_size + 1) * sizeof(float));
    features->yin_tmp  = (float*)malloc(max_frame_size * 2 * sizeof(float));
    if (!features->yin_diff || !features->yin_cmnd || !features->yin_tmp) {
        free_feature_set(features);
        return NULL;
    }

    // -------- 创建 WebRTC VAD 实例 --------
    if (features->vad_method == 0) {
        features->vad_inst = WebRtcVad_Create();
        if (features->vad_inst) {
            if (WebRtcVad_Init(features->vad_inst) == 0) {
                WebRtcVad_set_mode(features->vad_inst, 2);
                features->vad_sr = sample_rate;
            } else {
                WebRtcVad_Free(features->vad_inst);
                features->vad_inst = NULL;
                features->vad_sr = 0;
            }
        }
    } else {
        features->vad_inst = NULL;
        features->vad_sr = 0;
    }
    
    // 分配 PCM 缓冲（仅 WebRTC 模式）
    if (features->vad_method == 0) {
        features->vad_pcm_size = 2048;
        features->vad_pcm_buf = (int16_t*)malloc(features->vad_pcm_size * sizeof(int16_t));
        if (!features->vad_pcm_buf) {
            free_feature_set(features);
            return NULL;
        }
    }
    
    return features;
}

// 释放特征集合
void free_feature_set(FeatureSet* features) {
    if (!features) {
        return;
    }
    
    // 释放FFT频谱数据
    if (features->spectrum_fft) {
        free(features->spectrum_fft);
    }
    if (features->spectrum_mag) {
        free(features->spectrum_mag);
    }
    
    // 释放窗函数缓冲区
    if (features->window_buffer) {
        free(features->window_buffer);
    }
    
    // 释放FFT数据缓冲区
    if (features->fft_data) {
        free(features->fft_data);
    }
    
    // 释放对数重采样缓冲区
    if (features->log_indices) {
        free(features->log_indices);
    }
    if (features->log_resampled_full) {
        free(features->log_resampled_full);
    }
    
    // 释放 WebRTC VAD 实例
    if (features->vad_inst) {
        WebRtcVad_Free(features->vad_inst);
    }
    
    // 释放 PCM 缓冲（不再依赖vad_method，只检查指针） 
    if (features->vad_pcm_buf) {
        free(features->vad_pcm_buf);
    }
    
    // 释放 YIN 缓冲区
    if (features->yin_diff) {
        free(features->yin_diff);
    }
    if (features->yin_cmnd) {
        free(features->yin_cmnd);
    }
    if (features->yin_tmp) {
        free(features->yin_tmp);
    }
    
    // 释放结构体
    free(features);
}

// ------- 使用 WebRTC VAD ---------
int detect_vad(const float* preprocessed_audio, int length, FeatureSet* features) {
    if (!preprocessed_audio || length <= 0 || !features) {
        return ERROR_AUDIO_FRAME_INVALID;
    }

    // 根据配置选择 VAD 方法
    if (features->vad_method == 1) {
        /* ---------------- 纯能量法 ---------------- */
        float sum_sq = 0.0f;
        for (int i = 0; i < length; ++i) {
            float s = preprocessed_audio[i];
            sum_sq += s * s;
        }
        float rms = (length > 0) ? sqrtf(sum_sq / (float)length) : 0.0f;
        features->vad_value = (rms > features->vad_energy_th) ? 1.0f : 0.0f;
        return ERROR_SUCCESS;
    }

    /* ---------------- WebRTC VAD ---------------- */
    // 使用在 create_feature_set 中已初始化的实例
    VadInst* vad_inst = features->vad_inst;
    if (!vad_inst) {
        return ERROR_MEMORY_ALLOC_FAILED; // 若为 NULL 说明创建阶段已选择能量法却误入此分支
    }

    // -------- 调整：不论输入采样率，统一以 48 kHz 调用 WebRTC VAD --------
    const int vad_fs = 48000;                 // 目标 VAD 采样率
    int allowed_ns[] = {10, 20, 30};          // 允许的帧时长
    int target_len = 0;                       // 48 kHz 下的样本数

    for (int i = 2; i >= 0; --i) {            // 选最长但样本数 <= length
        int ms = allowed_ns[i];
        int samples_48k = (vad_fs * ms) / 1000;   // 480, 960, 1440
        if (samples_48k <= length) {           // 若原始帧足够长
            target_len = samples_48k;
            break;
        }
    }
    if (target_len == 0) {
        return ERROR_AUDIO_FRAME_INVALID;
    }

    // 转 int16_t 缓冲，仅使用前 target_len 样本
    int16_t* pcm_buf = features->vad_pcm_buf;
    if (!pcm_buf || target_len > features->vad_pcm_size) return ERROR_AUDIO_FRAME_INVALID;
    if (features->sample_rate == vad_fs) {
        // 采样率已是 48 kHz，无需重采样，直接截取
        for (int i = 0; i < target_len; ++i) {
            float s = preprocessed_audio[i];
            if (s > 1.0f) s = 1.0f; 
            if (s < -1.0f) s = -1.0f;
            pcm_buf[i] = (int16_t)lrintf(s * 32767.0f);
        }
    } else {
        // 最近邻重采样到 48 kHz
        float ratio = (float)features->sample_rate / (float)vad_fs;
        for (int i = 0; i < target_len; ++i) {
            int src_idx = (int)roundf(i * ratio);
            if (src_idx >= length) src_idx = length - 1;
            float s = preprocessed_audio[src_idx];
            if (s > 1.0f) s = 1.0f; 
            if (s < -1.0f) s = -1.0f;
            pcm_buf[i] = (int16_t)lrintf(s * 32767.0f);
        }
    }

    int vad_res = WebRtcVad_Process(vad_inst, vad_fs, pcm_buf, target_len);
    if (vad_res < 0) {
        return ERROR_AUDIO_FRAME_INVALID;
    }


    features->vad_value = vad_res ? 1.0f : 0.0f;
    return ERROR_SUCCESS;
}

// 提取音高特征实现
int extract_pitch_feature(const float* preprocessed_audio, int length, FeatureSet* features) {
    if (!preprocessed_audio || length <= 0 || !features) {
        return ERROR_AUDIO_FRAME_INVALID;
    }

    int sample_rate = features->sample_rate;

    /* -------- YIN 路径 -------- */
    static float last_valid_f0 = 0.0f;
    float detected_f0 = yin_detect_f0(features, length, sample_rate);

    /* 若检测失败则回退到上一次有效值 */
    float f0 = (detected_f0 > 0.0f) ? detected_f0 : last_valid_f0;

    /* 仅在检测到新有效 f0 时更新记忆 */
    if (detected_f0 > 0.0f) {
        last_valid_f0 = detected_f0;
    }

    if (f0 > 0.0f) {
        features->pitch = 69.0f + 12.0f * (logf(f0 / 440.0f) / logf(2.0f));
    } else {
        features->pitch = 0.0f; /* 全程无声 */
    }
    return ERROR_SUCCESS;
}

// 提取能量特征实现
int extract_energy_feature(const float* preprocessed_audio, int length, FeatureSet* features) {
    if (!preprocessed_audio || length <= 0 || !features) {
        return ERROR_AUDIO_FRAME_INVALID;
    }
    
    // 计算均方根(RMS)能量
    float mean_squared = 0.0f;
    int valid_samples = 0;
    
    for (int i = 0; i < length; i++) {
        // 可以添加额外的有效性检查
        float sample = preprocessed_audio[i];
        if (!isnan(sample) && !isinf(sample)) {
            mean_squared += sample * sample;
            valid_samples++;
        }
    }
    
    // 安全检查：确保有有效样本且均方值为正数
    if (valid_samples > 0) {
        mean_squared /= valid_samples;
    } else {
        // 无有效样本
        mean_squared = 0.0f;
    }
    
    // 计算RMS值
    float rms_energy = 0.0f;
    if (mean_squared > 0.0f) {
        rms_energy = sqrtf(mean_squared);
    }
    
    // 转换为分贝单位（与Python代码一致）
    // 使用20*log10(能量)，添加小值(1e-10)避免log(0)
    float energy_db = -100.0f; // 默认低能量值
    if (rms_energy > 0.0f) {
        energy_db = 20.0f * log10f(rms_energy + 1e-10f);
    }
    
    // 限制最小值
    if (energy_db < -100.0f) {
        energy_db = -100.0f;
    }
    
    // 存储分贝单位的能量值
    features->energy = energy_db;
    
    return ERROR_SUCCESS;
}

// 提取频谱特征实现
int extract_spectrum_feature(const float* preprocessed_audio, int length, FeatureSet* features) {
    if (!preprocessed_audio || length <= 0 || !features || !features->spectrum_fft) {
        return ERROR_AUDIO_FRAME_INVALID;
    }
    
    // 参数验证
    if (length > features->max_frame_size) {
        return ERROR_AUDIO_FRAME_INVALID;
    }
    
    // 处理参数
    int frame_size = length; // 已经是帧大小
    int sample_rate = features->sample_rate; // 使用从引擎获取的采样率
    
    // 固定参数
    int min_freq = 50;       // Hz
    int max_freq = 6000;     // Hz
    int target_bins = 256;   // 目标频点数量
    
    // 复制输入数据到FFT数据缓冲区的实部
    for (int i = 0; i < frame_size; i++) {
        features->fft_data[i*2] = preprocessed_audio[i]; // 实部
        features->fft_data[i*2+1] = 0.0f;                // 虚部
    }
    
    // 应用窗函数到FFT数据的实部
    for (int i = 0; i < frame_size; i++) {
        features->fft_data[i*2] *= features->window_buffer[i];
    }
    
    // 调用FFT计算函数 (1表示正向FFT)
    CFFTN(features->fft_data, frame_size, 1);
    
    // 计算幅度并转换为分贝
    for (int i = 0; i < frame_size/2 + 1; i++) {
        float real = features->fft_data[i*2];
        float imag = features->fft_data[i*2+1];
        float magnitude = sqrtf(real*real + imag*imag);
        // 保存线性幅度值
        if (features->spectrum_mag) {
            features->spectrum_mag[i] = magnitude;
        }
        // 转换为分贝值 (存储在 spectrum_fft)
        features->spectrum_fft[i] = 20.0f * log10f(magnitude + 1e-10f);
    }
    
    // 计算频率分辨率
    float freq_resolution = (float)sample_rate / (float)frame_size;
    
    // 计算频率范围对应的bin
    int min_bin = fmaxf(1, (int)(min_freq / freq_resolution));
    int max_bin = fminf((int)(max_freq / freq_resolution), frame_size / 2);
    int num_freq_bins = max_bin - min_bin;
    
    // -------- 方案A（改进）：使用预分配缓冲区 --------
    // 若 num_freq_bins 变化（或首次运行），重新计算 log_indices
    if (features->num_freq_bins != num_freq_bins || features->min_bin != min_bin) {
        for (int i = 0; i < num_freq_bins; i++) {
            float t = (float)i / (num_freq_bins - 1);
            features->log_indices[i] = expf(t * logf((float)num_freq_bins)) - 1.0f;
            if (features->log_indices[i] < 0.0f) features->log_indices[i] = 0.0f;
            if (features->log_indices[i] > num_freq_bins - 1.0001f) features->log_indices[i] = num_freq_bins - 1.0001f;
        }
        features->num_freq_bins = num_freq_bins;
        features->min_bin = min_bin;
    }

    // 使用线性插值得到 num_freq_bins 点对数重采样结果
    for (int i = 0; i < num_freq_bins; i++) {
        float index = features->log_indices[i];
        int index_floor = (int)index;
        int index_ceil = index_floor + 1;
        if (index_ceil >= num_freq_bins) index_ceil = num_freq_bins - 1;
        float frac = index - index_floor;
        features->log_resampled_full[i] = features->spectrum_fft[min_bin + index_floor] * (1.0f - frac) +
                                          features->spectrum_fft[min_bin + index_ceil] * frac;
    }
    
    // 4) 截断或补零到 target_bins(=256)
    for (int i = 0; i < target_bins; i++) {
        float value = (i < num_freq_bins) ? features->log_resampled_full[i] : 0.0f;

        // clip[-127,127] 并转 int8 → float
        if (value < -127.0f) value = -127.0f;
        if (value > 127.0f) value = 127.0f;

        char int_value = (char)roundf(value);
        features->spectrum[i] = (float)int_value;
    }
    
    return ERROR_SUCCESS;
}

// 提取音色特征实现
int extract_timbre_feature(const float* preprocessed_audio, int length, FeatureSet* features) {
    if (!preprocessed_audio || length <= 0 || !features) {
        return ERROR_AUDIO_FRAME_INVALID;
    }
    
    // 默认音色特征设置为0
    features->timbre_features = 0.0f;
    
    // 需要线性幅度谱；若不可用则计算失败提前返回
    if (!features->spectrum_mag) {
        return ERROR_SUCCESS;
    }
    
    // 计算频率分辨率
    float freq_resolution = (float)features->sample_rate / (float)length;
    
    // 计算频谱质心 (Spectral Centroid)
    double numerator = 0.0;
    double denominator = 0.0;
    int half_frame = length / 2;
    for (int i = 0; i <= half_frame; i++) {
        float magnitude = features->spectrum_mag[i];
        if (magnitude < 1e-10f) magnitude = 0.0f; // 保持与Python一致，极小值可忽略
        float freq = (float)i * freq_resolution;
        numerator += (double)freq * magnitude;
        denominator += magnitude;
    }
    
    float spectral_centroid = 0.0f;
    if (denominator > 1e-12) {
        spectral_centroid = (float)(numerator / denominator);
    }
    
    // 归一化到 0-1 之间（Nyquist 频率为 sample_rate/2）
    float normalized_centroid = spectral_centroid / ((float)features->sample_rate * 0.5f);
    if (normalized_centroid < 0.0f) normalized_centroid = 0.0f;
    if (normalized_centroid > 1.0f) normalized_centroid = 1.0f;
    
    // 存储归一化质心作为音色特征
    features->timbre_features = normalized_centroid;
    
    return ERROR_SUCCESS;
}

// 提取明亮度特征实现
int extract_brightness_feature(const float* preprocessed_audio, int length, FeatureSet* features) {
    if (!preprocessed_audio || length <= 0 || !features) {
        return ERROR_AUDIO_FRAME_INVALID;
    }
    
    // 默认明亮度设置为0
    features->brightness = 0.0f;
    
    // 使用频谱数据计算明亮度
    if (!features->spectrum_fft) {
        return ERROR_SUCCESS;
    }
    
    // 权重设置
    const float w1 = 0.7f;  // 2kHz-5kHz 的权重
    const float w2 = 0.3f;  // 5kHz-8kHz 的权重
    
    // 计算频率分辨率 = 采样率 / 帧大小
    float freq_resolution = (float)features->sample_rate / (float)length;
    
    // 计算各频段对应的FFT索引
    int low_idx = 0;  // 0Hz
    int mid1_idx = (int)(2000.0f / freq_resolution);  // 2kHz
    int mid2_idx = (int)(5000.0f / freq_resolution);  // 5kHz
    int high_idx = (int)(8000.0f / freq_resolution);  // 8kHz
    
    // 确保索引在有效范围内(Nyquist频率以下)
    int half_frame_size = length / 2;
    mid1_idx = (mid1_idx > 0) ? (mid1_idx < half_frame_size ? mid1_idx : half_frame_size) : 1;
    mid2_idx = (mid2_idx > 0) ? (mid2_idx < half_frame_size ? mid2_idx : half_frame_size) : 1;
    high_idx = (high_idx > 0) ? (high_idx < half_frame_size ? high_idx : half_frame_size) : 1;
    
    // 计算总能量(0-8kHz)
    // 使用预先存储的线性幅度谱 spectrum_mag 直接计算功率谱(|FFT|^2)。
    float total_energy = 0.0f;
    float energy_2k_5k = 0.0f;
    float energy_5k_8k = 0.0f;
    
    for (int i = low_idx; i < high_idx; i++) {
        float magnitude = 0.0f;
        if (features->spectrum_mag) {
            magnitude = features->spectrum_mag[i];
        } else {
            // 回退：若未分配，则从 dB 值逆推
            float db_val = features->spectrum_fft[i];
            magnitude = powf(10.0f, db_val / 20.0f);
        }
        float bin_energy = magnitude * magnitude;

        total_energy += bin_energy;
        
        // 累加2kHz-5kHz频段能量
        if (i >= mid1_idx && i < mid2_idx) {
            energy_2k_5k += bin_energy;
        }
        // 累加5kHz-8kHz频段能量
        else if (i >= mid2_idx && i < high_idx) {
            energy_5k_8k += bin_energy;
        }
    }
    
    // 计算能量占比和明亮度
    if (total_energy > 0.0f) {
        float ratio_2k_5k = energy_2k_5k / total_energy;
        float ratio_5k_8k = energy_5k_8k / total_energy;
        
        // 计算加权明亮度
        features->brightness = w1 * ratio_2k_5k + w2 * ratio_5k_8k;
        
        // 确保值在[0,1]范围内
        if (features->brightness > 1.0f) {
            features->brightness = 1.0f;
        } else if (features->brightness < 0.0f) {
            features->brightness = 0.0f;
        }
    }
    
    return ERROR_SUCCESS;
}

// 提取所有特征
int extract_features(const float* preprocessed_audio, int length, FeatureSet* features) {
    if (!preprocessed_audio || length <= 0 || !features) {
        return ERROR_AUDIO_FRAME_INVALID;
    }
    
    int ret;
    
    // 1. 先进行VAD检测
    ret = detect_vad(preprocessed_audio, length, features);
    if (ret != ERROR_SUCCESS) {
        return ret;
    }
    
    // 2. 提取能量特征
    ret = extract_energy_feature(preprocessed_audio, length, features);
    if (ret != ERROR_SUCCESS) {
        return ret;
    }
     
    
    // 4. 提取频谱特征 (这会计算完整的FFT和压缩后的频谱)
    ret = extract_spectrum_feature(preprocessed_audio, length, features);
    if (ret != ERROR_SUCCESS) {
        return ret;
    }
    
    // 5. 提取音高特征
    ret = extract_pitch_feature(preprocessed_audio, length, features);
    if (ret != ERROR_SUCCESS) {
        return ret;
    }
    
    // 6. 提取音色特征
    ret = extract_timbre_feature(preprocessed_audio, length, features);
    if (ret != ERROR_SUCCESS) {
        return ret;
    }
    
    // 7. 提取明亮度特征
    ret = extract_brightness_feature(preprocessed_audio, length, features);
    if (ret != ERROR_SUCCESS) {
        return ret;
    }
    
    return ERROR_SUCCESS;
} 